#
# Copyright 2008 Wepoco.  http://www.wepoco.org/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import cgi
import datetime

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import urlfetch

from template import header, footer
from Picasa import Picasa
from GPXTimeline import GPXTimeline

class Debug(webapp.RequestHandler):

  def get(self):
    form = cgi.FieldStorage()
    key = form.getvalue('key')
    track = db.get(db.Key(key))
    urlres = None

    self.response.out.write(header(self.request))
    self.response.out.write("""<p><b>Track</b>&nbsp;%s</p>""" % track.name)
    if track.album:
      self.response.out.write("""<p><b>Album</b>&nbsp;%s</p>""" % (track.albumName))  
      self.response.out.write("""<p><b>Owner</b>&nbsp;%s</p>""" % track.albumOwner)
      self.response.out.write("""<p>%s</p>""" % track.album)
      pass

    self.response.out.write("""<p>%s</p>""" % (track.geoStart))

    #self.response.out.write("""</table></form>""")

    timeline = GPXTimeline(track.getContent())
    self.response.out.write("<table><tr><th></th></tr>")
    for (tstart,tend) in timeline.timeline(debug=True):
      self.response.out.write("""
<tr><td>%.4f</td><td>%.4f</td> 
<td>%s</td><td>%s</td></tr>""" % 
                                (tstart.lat, tstart.lon, tstart.when,
                                 tend.when))
          
      pass
    self.response.out.write("""</table>""")
    
    photos = None
    urlres = urlfetch.fetch("http://picasaweb.google.com/data/feed/api/user/%s/album/%s?kind=photo" % (track.albumOwner,track.albumName))
    if urlres.status_code==200:
      photos = Picasa(urlres.content).photos()
      timeline.getPhotoLocations(photos)
    else:
      self.response.out.write("""<p><b>Failed to download photo album<b> (%d)</p>""" %
                              urlres.status_code)
      pass
      
    if photos:
      self.response.out.write("<table><tr><th></th></tr>")
      for photo in photos:
        self.response.out.write("""
<tr><td>%s</td>
<td>%s</td><td>%s</td><td>%s</td></tr>""" % 
                                (photo.title,photo.getDatetime(),
                                 photo.lat, photo.lon))
          
        pass
      self.response.out.write("""</table>""")
      pass
      
    self.response.out.write(footer(self.request))


